package com.squirrel.serialportcore.machine.init.after;

import com.squirrel.serialportcore.common.CommonBase;
import com.squirrel.serialportcore.entity.mapper.PortQueueMapper;
import com.squirrel.serialportcore.entity.model.BindingModel;
import com.squirrel.serialportcore.entity.model.ExchangeModel;
import com.squirrel.serialportcore.entity.model.ExchangeType;
import com.squirrel.serialportcore.entity.model.QueueModel;
import com.squirrel.serialportcore.machine.creator.MessageQueueCreator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.stereotype.Component;

/**
 * 队列初始化
 *
 * @author Squbi
 * @date 2021/3/23 11:33
 */
@Component
public class QueueInitializer {
    private static final Logger logger = LoggerFactory.getLogger(QueueInitializer.class);

    private MessageQueueCreator messageQueueCreator;

    QueueInitializer(MessageQueueCreator messageQueueCreator) {
        this.messageQueueCreator = messageQueueCreator;
    }

    public void initQueue(String portName) {
        PortQueueMapper portQueueMapper = CommonBase.getPortQueueName().get(portName);
        String inQ = portQueueMapper.getInQ();
        String outQ = portQueueMapper.getOutQ();
        String outE = portQueueMapper.getOutE();
        String outR = portQueueMapper.getOutR();
        logger.debug(" -debug- 开始对 {} 进行队列创建绑定", portName);
        if (!messageQueueCreator.queueIsExist(inQ)) {
            logger.info(" 检测到队列 {} 不存在 正在创建", inQ);
            messageQueueCreator.create(new QueueModel(inQ));
        }
        Queue oq;
        QueueModel queueConfig = new QueueModel(outQ);
        if (!messageQueueCreator.queueIsExist(outQ)) {
            logger.info(" 检测到队列 {} 不存在 正在创建", outQ);
            oq = messageQueueCreator.create(queueConfig);
        } else {
            oq = messageQueueCreator.createQueue(queueConfig);
        }
        Exchange oe = messageQueueCreator.create(new ExchangeModel(outE, ExchangeType.FANOUT));
        messageQueueCreator.create(new BindingModel(oq, oe, outR));
    }
}
